package org.iabako.server.taglib;

import org.iabako.shared.entity.enumeration.Language;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * Created by jose on 29/01/15.
 */
public abstract class AbstractTag extends TagSupport {

    protected Language getPickedLanguage(HttpServletRequest request) {

        String languageFromRequest = request.getLocale().getLanguage();
        Language pickedLang = getLanguageFromString(languageFromRequest);

        Language languageFromSession = (Language) request.getSession().getAttribute("IABAKO_LANG");

        if (languageFromSession != null) {
            pickedLang = languageFromSession;

        } else if (request.getCookies() != null) {
            Language languageFromCookie = getLanguageFromCookies(request.getCookies());
            pickedLang = languageFromCookie != null ? languageFromCookie : pickedLang;
        }

        request.getSession().setAttribute("IABAKO_LANG", pickedLang);

        return pickedLang;
    }

    private Language getLanguageFromCookies(Cookie[] cookies) {
        String languageFromCookie = null;
        for (Cookie cookie : cookies) {
            if ("IABAKO_LANG".equals(cookie.getName())) {
                languageFromCookie = cookie.getValue();
            }
        }
        return languageFromCookie != null ? getLanguageFromString(languageFromCookie) : null;
    }

    private Language getLanguageFromString(String laguageString) {
        for (Language lang : Language.values()) {
            if (lang.getLangString().equalsIgnoreCase(laguageString)) {
                return lang;
            }
        }
        return Language.EN;
    }

}
